package cn.edu.scnu.semart.cart.controller;
import cn.edu.scnu.semart.cart.service.CartService;
import cn.edu.scnu.semart.model.cart.Cart;
import cn.edu.scnu.semart.model.cart.CartItemDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    // 添加/更新购物车
    @PostMapping("/add")
    public Map<String, Object> addOrUpdate(@RequestBody Cart cart) {
        Map<String, Object> result = new HashMap<>();
        try {
            cartService.addOrUpdateCart(cart);
            result.put("success", true);
            result.put("message", "商品已成功添加到购物车");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加失败: " + e.getMessage());
        }
        return result;
    }

    // 更新购物车项
    @PostMapping("/update")
    public Map<String, Object> update(@RequestBody Cart cart) {
        Map<String, Object> result = new HashMap<>();
        try {
            cartService.updateCartItem(cart);
            result.put("success", true);
            result.put("message", "购物车更新成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
        }
        return result;
    }

    // 删除单个购物车项
    @DeleteMapping("/delete/{cartId}")
    public Map<String, Object> delete(@PathVariable Integer cartId) {
        Map<String, Object> result = new HashMap<>();
        try {
            cartService.deleteCartItem(cartId);
            result.put("success", true);
            result.put("message", "商品已从购物车移除");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败: " + e.getMessage());
        }
        return result;
    }

    // 批量删除购物车项
    @DeleteMapping("/deleteAll")
    public Map<String, Object> batchDelete(@RequestBody List<Integer> cartIds) {
        Map<String, Object> result = new HashMap<>();
        try {
            cartService.batchDeleteCartItems(cartIds);
            result.put("success", true);
            result.put("message", "已批量删除 " + cartIds.size() + " 件商品");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败: " + e.getMessage());
        }
        return result;
    }

    // 获取用户购物车
    @GetMapping("/getUserCart/{userId}")
    public Map<String, Object> getUserCart(@PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 1. 获取购物车项列表
            List<CartItemDTO> cartItems = cartService.getUserCart(userId);

            // 2. 计算统计数据
            int totalCount = 0;                   // 总商品数量
            int selectedCount = 0;                // 选中商品数量
            BigDecimal totalAmount = BigDecimal.ZERO;  // 选中商品总金额
            int outOfStockCount = 0;              // 缺货商品数量

            for (CartItemDTO item : cartItems) {
                totalCount += item.getQuantity();

                if (Boolean.TRUE.equals(item.getSelected())) {
                    selectedCount += item.getQuantity();

                    // 确保价格不为空
                    if (item.getProductPrice() != null) {
                        BigDecimal itemTotal = item.getProductPrice()
                                .multiply(BigDecimal.valueOf(item.getQuantity()));
                        totalAmount = totalAmount.add(itemTotal);
                    }
                }

                // 检查库存状态 (0: 有货, 1: 缺货)
                if (item.getStockStatus() != null && item.getStockStatus() == 1) {
                    outOfStockCount++;
                }
            }

            // 3. 构建响应数据
            result.put("success", true);
            result.put("data", cartItems);            // 购物车项列表
            result.put("totalCount", totalCount);      // 购物车中所有商品总数
            result.put("selectedCount", selectedCount); // 选中商品总数
            result.put("totalAmount", totalAmount);    // 选中商品总金额
            result.put("outOfStockCount", outOfStockCount); // 缺货商品数量
            result.put("itemCount", cartItems.size()); // 购物车项数量（不同商品种类数）
            result.put("timestamp", System.currentTimeMillis()); // 响应时间戳

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取购物车失败: " + e.getMessage());
            result.put("errorCode", "CART_QUERY_ERROR");
        }
        return result;
    }

    // 新增: 专门为Feign调用设计的接口，直接返回购物车项列表
    @GetMapping("/getCartItems/{userId}")
    public List<CartItemDTO> getCartItems(@PathVariable Integer userId) {
        try {
            return cartService.getUserCart(userId);
        } catch (Exception e) {
            throw new RuntimeException("获取购物车失败: " + e.getMessage());
        }
    }

}